<?php

namespace backend\models;

use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "category".
 *
 * @property integer $id
 * @property string $title
 * @property string $createTime
 * @property integer $parentId
 *
 * @property Category $parent
 * @property Category[] $categories
 */
class Category_1 extends \yii\db\ActiveRecord {

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'category';
    }

    public static function getCTableName() {
        return '分类';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
                [['title', 'parentId'], 'required'],
                [['createTime'], 'safe'],
                [['parentId'], 'integer'],
                [['title'], 'string', 'max' => 36],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'title' => '分类名称',
            'createTime' => '创建时间',
            'parentId' => '上级分类',
        ];
    }

    public function getData() {
        $cates = self::find()->all();
        $cates = ArrayHelper::toArray($cates);
        return $cates;
    }

    public function getTree($cates, $pid = 0) {
        $tree = [];
        foreach ($cates as $cate) {
            if ($cate['parentId'] == $pid) {
                $tree[] = $cate;
                $tree = array_merge($tree, $this->getTree($cates, $cate['id']));
            }
        }
        return $tree;
    }

    public function setPrefix($data, $p = "|-----") {
        $tree = [];
        $num = 1;
        $prefix = [0 => 1];
        while ($val = current($data)) {
            $key = key($data);
            if ($key > 0) {
                if ($data[$key - 1]['parentId'] != $val['parentId']) {
                    $num ++;
                }
            }
            if (array_key_exists($val['parentId'], $prefix)) {
                $num = $prefix[$val['parentId']];
            }
            $val['title'] = str_repeat($p, $num) . $val['title'];
            $prefix[$val['parentId']] = $num;
            $tree[] = $val;
            next($data);
        }
        return $tree;
    }

    public function getCategoryList() {
        $data = $this->getData();
        $tree = $this->getTree($data);
        $tree = $this->setPrefix($tree);
        $options = ['顶级分类'];
        foreach ($tree as $cate) {
            $options[$cate['id']] = $cate['title'];
        }
        return $options;
    }

    public static function getCategoryList_S($type = 0) {
        $model = new Category();
        $list = $model->getCategoryList();
        if (type != 0) {
            unset($list[0]);
        }
        return $list;
    }

    public function beforeSave($insert) {
        if (parent::beforeSave($insert)) {
            $this->createTime = date("Y-m-d h-i-s", time());
            return TRUE;
        }
        return FALSE;
    }

}
